<?php

namespace App\Http\Controllers;

use App\Article;
use App\Http\Requests;
use App\Studyfav;
use App\Task;
use App\User;
use Auth;
use Cache;
use Cookie;
use DB;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Input;
use Log;
use Mail;
use Redirect;
use Reponse;
use View;
use App\Utils;

class artController extends Controller
{

    public function __construct(Article $article)
    {
        //$this->middleware('auth', ['except' => ['articles']]);
        $this->article = $article;
    }

    public function articles(Request $request, $tag = "all", $types = "new")
    {
        Utils::log($request, 'articles');
        $order = "created_at";
        if ($types == "hot")
            $order = "score";

        $articles = $this->article->getByTagAndOrder($tag, $order);
		if(Auth::check()) {
            $fav = Auth::user()->favorites;
		}

        foreach ($articles as $k => $art) {
            $fav = 0;
            if (Auth::check() && Auth::user()->id != $art->userid) {
                $fav = Studyfav::whereUseridAndStudyidAndType(Auth::user()->id, $art->id, 2)->orderBy('created_at', 'desc')->get()->first();
            }
            $art->count = count(Studyfav::where('type', 2)->where('studyid', $art->id)->get());
            if ($fav != null) $articles[$k]['fav'] = 0;
            else $articles[$k]['fav'] = 1;
        }
        $type = "article";
        if ($tag == "all")
            return view("article.list")
                ->with(compact("articles"))
                ->with(compact("tag"))
                ->with(compact("types"))
                ->with(compact("type"));
        else {
            $task = Task::whereTitle($tag)->get()->first();
            $task->user = User::find($task->contributor);
            return view("article.art")
                ->with(compact("articles"))
                ->with(compact("tag"))
                ->with(compact("task"))
                ->with(compact("type"));
        }
    }

    public function create(Request $request, $tag = "all")
    {
        if ($request->isMethod('post')) {
            $input = $request->all();
            $data = array();
            $data['userid'] = Auth::user()->id;
            $data['content'] = $input['content'];
            $data['title'] = $input['title'];
            $data['suggest'] = $input['suggest'];
            if ($input['filter'] != "其他")
                $data['tag'] = $input['tag'];
            else $data['tag'] = "其他";

            Article::create($data);
            return Redirect::to('article/all');
        }
        $data = DB::select("select id,title from tasks order by id asc");
        return View::make("article.share")
            ->with(compact("tag"))
            ->with(compact("data"));
    }
}
